<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from "vue";
import { errorImg } from "@/assets/errorImg";
import {
  AppstoreOutlined,
  ArrowLeftOutlined,
  BarsOutlined,
  ClockCircleOutlined,
  EyeOutlined,
  FireOutlined,
  LikeOutlined,
} from "@ant-design/icons-vue";
import type { BlogVo, CategoryListVo } from "@/type";
import { useRoute, useRouter } from "vue-router";
import { categoryApi } from "@/api";
import { filterHtmlTags, truncateString } from "@/utils";
import dayjs from "dayjs";

const route = useRoute();
const router = useRouter();

const params = reactive({
  page: 1,
  pageSize: 10,
  sort: "",
});
const total = ref(0);
const sortType = ref("latest");
const viewMode = ref("grid");
const selectedCategory = ref<CategoryListVo | null>(null);
// 分类列表
const categories = ref<CategoryListVo[]>([]);
// 分类下的文章列表
const articles = ref<BlogVo[]>([]);
const selectCategory = (category: CategoryListVo) => {
  selectedCategory.value = category;
  getDetail(category.id);
  // 清除query参数
  router.replace({ query: {} });
};
const changeSort = (type: string) => {
  sortType.value = type;
  params.sort = type;
  getDetail(selectedCategory.value!.id);
};
const getDetail = async (id: number) => {
  const res = await categoryApi.getDetail({ id: id, ...params });
  articles.value = res.rows.map((item: BlogVo) => {
    return {
      ...item,
      createdAt: dayjs(String(item.createdAt)).format("YYYY-MM-DD"),
      excerpt: truncateString(filterHtmlTags(item.excerpt), 50),
    };
  });
  total.value = res.count;
};
const backCategory = () => {
  selectedCategory.value = null;
  // 清除query参数
  router.replace({ query: {} });
};
// 获取hash路由参数
const cid = route.query.id;
const getCategoryList = async () => {
  const res = await categoryApi.getCategoryList();
  categories.value = res.result;
};
onMounted(() => {
  getCategoryList();
});
watch(
  () => categories.value,
  () => {
    if (cid) {
      const cidNumber = Number(cid);
      if (!isNaN(cidNumber)) {
        const category = categories.value.find((c) => c.id === cidNumber);
        if (category) {
          selectedCategory.value = category;
          getDetail(category.id);
        }
      }
    }
  },
);
</script>

<template>
  <div class="min-h-screen">
    <!-- 面包屑 - 移动端调整 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 pt-16 sm:pt-20">
      <a-breadcrumb class="py-3 sm:py-4 text-sm sm:text-base">
        <a-breadcrumb-item>
          <router-link to="/" data-readdy="true">首页</router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item>文章分类</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <!-- 分类卡片网格 -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 py-4 sm:py-6">
      <div
        class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 sm:gap-6"
      >
        <div
          v-for="category in categories"
          :key="category.id"
          class="bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow duration-300 cursor-pointer overflow-hidden"
          @click="selectCategory(category)"
        >
          <div class="h-32 sm:h-40 relative">
            <img
              :src="category.image || errorImg"
              alt="分类图片"
              class="w-full h-full object-cover"
            />
            <div
              class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent flex items-end"
            >
              <div class="p-3 sm:p-4 text-white">
                <h3 class="text-lg sm:text-xl font-medium mb-1">
                  {{ category.name }}
                </h3>
                <div class="flex items-center space-x-2 text-xs sm:text-sm">
                  <eye-outlined class="text-xs sm:text-sm" />
                  <span>{{ category.articleCount }} 篇文章</span>
                </div>
              </div>
            </div>
          </div>
          <div class="p-3 sm:p-4">
            <p class="text-gray-600 text-xs sm:text-sm line-clamp-2">
              {{ category.description }}
            </p>
          </div>
        </div>
      </div>
    </main>

    <!-- 分类文章列表 -->
    <div
      v-if="selectedCategory"
      class="max-w-7xl mx-auto px-4 sm:px-6 py-4 sm:py-6"
    >
      <div
        class="flex flex-col sm:flex-row items-start sm:items-center justify-between mb-4 sm:mb-6 gap-3"
      >
        <div>
          <h2
            class="text-xl sm:text-2xl font-bold"
            :id="'c-' + selectedCategory.id"
          >
            {{ selectedCategory.name }}
          </h2>
          <p class="text-gray-500 text-sm sm:text-base mt-1">
            共 {{ articles.length }} 篇文章
          </p>
        </div>
        <a-button
          @click="backCategory"
          class="!rounded-button whitespace-nowrap !h-8 sm:!h-auto"
        >
          <template #icon>
            <arrow-left-outlined class="text-xs sm:text-sm" />
          </template>
          <span class="text-xs sm:text-sm">返回分类</span>
        </a-button>
      </div>

      <!-- 排序工具栏 - 移动端改为垂直布局 -->
      <div class="max-w-7xl mx-auto mb-4 sm:mb-6">
        <div
          class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3"
        >
          <div class="flex flex-wrap gap-2">
            <a-button
              :type="sortType === 'latest' ? 'primary' : 'default'"
              @click="changeSort('latest')"
              size="small"
              class="!rounded-button !h-8 sm:!h-auto"
            >
              <template #icon>
                <clock-circle-outlined class="text-xs sm:text-sm" />
              </template>
              <span class="text-xs sm:text-sm">最新发布</span>
            </a-button>
            <a-button
              :type="sortType === 'popular' ? 'primary' : 'default'"
              @click="changeSort('popular')"
              size="small"
              class="!rounded-button !h-8 sm:!h-auto"
            >
              <template #icon>
                <fire-outlined class="text-xs sm:text-sm" />
              </template>
              <span class="text-xs sm:text-sm">最多阅读</span>
            </a-button>
          </div>
          <div class="flex gap-2">
            <a-button
              :type="viewMode === 'grid' ? 'primary' : 'default'"
              @click="viewMode = 'grid'"
              size="small"
              class="!rounded-button !h-8 sm:!h-auto"
            >
              <template #icon>
                <appstore-outlined class="text-xs sm:text-sm" />
              </template>
              <span class="text-xs sm:text-sm">网格</span>
            </a-button>
            <a-button
              :type="viewMode === 'list' ? 'primary' : 'default'"
              @click="viewMode = 'list'"
              size="small"
              class="!rounded-button !h-8 sm:!h-auto"
            >
              <template #icon>
                <bars-outlined class="text-xs sm:text-sm" />
              </template>
              <span class="text-xs sm:text-sm">列表</span>
            </a-button>
          </div>
        </div>
      </div>

      <!-- 分类横幅 - 移动端高度调整 -->
      <div class="mb-6 sm:mb-8">
        <div
          class="relative h-40 sm:h-64 rounded-lg sm:rounded-xl overflow-hidden"
        >
          <img
            :src="selectedCategory.image || errorImg"
            :alt="selectedCategory.name"
            class="w-full h-full object-cover"
          />
          <div
            class="absolute inset-0 bg-gradient-to-r from-black/70 to-transparent flex items-center"
          >
            <div class="p-4 sm:p-8 text-white max-w-xl">
              <h1 class="text-xl sm:text-3xl font-bold mb-2 sm:mb-4">
                {{ selectedCategory.name }}
              </h1>
              <p class="text-sm sm:text-lg">
                {{ selectedCategory.description }}
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- 文章列表 - 移动端优化 -->
      <div
        :class="
          viewMode === 'grid'
            ? 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6'
            : 'space-y-4 sm:space-y-6'
        "
      >
        <div
          v-for="article in articles"
          :key="article.id"
          @click="
            router.push({
              name: 'blogItem',
              params: { id: article.id, title: article.title },
            })
          "
          :class="
            viewMode === 'grid'
              ? 'bg-white rounded-lg shadow-sm overflow-hidden'
              : 'bg-white rounded-lg shadow-sm flex flex-col sm:flex-row overflow-hidden'
          "
          class="cursor-pointer hover:shadow-md transition-shadow duration-300"
        >
          <img
            :src="article.coverImage"
            :alt="article.title"
            :class="
              viewMode === 'grid'
                ? 'w-full h-32 sm:h-48 object-cover'
                : 'w-full sm:w-48 h-32 sm:h-auto object-cover'
            "
          />
          <div class="p-3 sm:p-5 flex flex-col flex-grow">
            <h3
              class="text-base sm:text-lg font-medium mb-1 sm:mb-2 line-clamp-2"
            >
              {{ article.title }}
            </h3>
            <p
              class="text-gray-600 text-xs sm:text-sm mb-2 sm:mb-4 line-clamp-2 flex-grow"
            >
              {{ article.excerpt }}
            </p>
            <div
              class="flex items-center justify-between text-xs sm:text-sm text-gray-500"
            >
              <div class="flex items-center space-x-2 sm:space-x-4">
                <span class="flex items-center">
                  <eye-outlined class="mr-1 text-xs sm:text-sm" />
                  {{ article.views }}
                </span>
                <span class="flex items-center">
                  <like-outlined class="mr-1 text-xs sm:text-sm" />
                  {{ article.likes }}
                </span>
              </div>
              <span>{{ article.createdAt }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 - 移动端简化 -->
      <div v-if="articles.length > 6" class="mt-6 sm:mt-8 flex justify-center">
        <a-pagination
          v-model:current="params.page"
          :total="total"
          :pageSize="params.pageSize"
          show-less-items
          size="small"
          class="sm:pagination-large"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.prose {
  color: #374151;
  max-width: 65ch;
  font-size: 1rem;
  line-height: 1.6;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

@media (min-width: 640px) {
  .prose {
    font-size: 1.125rem;
    line-height: 1.75;
  }
}

/* 移动端优化Ant Design组件 */
@media (max-width: 640px) {
  :deep(.ant-pagination-item),
  :deep(.ant-pagination-prev),
  :deep(.ant-pagination-next) {
    min-width: 28px;
    height: 28px;
    margin: 0 2px;
  }

  :deep(.ant-pagination-item a) {
    padding: 0 6px;
    font-size: 12px;
  }

  :deep(.ant-btn) {
    padding: 0 8px;
    height: 32px;
    font-size: 12px;
  }

  :deep(.ant-btn .anticon) {
    font-size: 12px;
  }
}
</style>
